package com.jwcao.common.cast.operation.access.field.collection;

import com.jwcao.common.cast.annotation.CastField;
import com.jwcao.common.cast.operation.CastFlow;
import com.jwcao.common.scan.object.ScanField;
import java.util.Collection;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;

/**
 * name: GenericsCollectionAccessOperation description: TODO
 *
 * @author caojingwei date: 2023/3/24 14:21
 */
public class GenericsListAccessOperation extends ListFieldAccessOperation {

    private final Map<Class, CastFlow> castFlowMap;

    public GenericsListAccessOperation(CastField castField, ScanField sourceField,
        ScanField targetField, Class sourceItemClass, Class targetItemClass,
        Map<Class, CastFlow> castFlowMap) {
        super(castField, sourceField, targetField, sourceItemClass, targetItemClass);
        this.castFlowMap = castFlowMap;
    }


    @Override
    public Object execute(Object sourceObject) {

        Collection sourceCollection = (Collection) sourceField.get(sourceObject);

        if (CollectionUtils.isEmpty(sourceCollection)) {
            return sourceCollection;
        }

        return sourceCollection.stream().map(s -> {
            CastFlow castFlow = castFlowMap.get(s.getClass());
            return castFlow.execute(s);
        }).collect(Collectors.toList());
    }
}
